import {
    IndexData
} from "../../models/index.js"

import {
    Like
} from "../../models/like.js"

Page({
    data: {
        currentData: null,
        latest: true,
        first: false,
        likeStatus: null
    },

    onLoad: function() {
        this._getLatest()
    },


    // 监听组件点击下一期
    next() {
        this._upData("next")
    },

    // 监听组件点击上一期
    previous() {
        this._upData("previous")
    },

    // 监听是否喜欢
    onLike(e) {
        let status = e.detail.status
        let count = e.detail.count
        count = status ? count + -1 : count + 1
        let artID = this.data.currentData.id
        let type = this.data.currentData.type
        const res = Like.like(!status, artID, type)
        // 本地手动改变数据 避免多一个请求  这里后端可返回改变后的数据
        let likeStatus = {
            fav_nums: count,
            like_status: !status
        }
        this.setData({
            likeStatus
        })
    },

    async _upData(nextOrPrevious) {
        let index = this.data.currentData.index
        const currentData = await IndexData.getNextOrPrevious(index, nextOrPrevious)
        this._getLikeStatus(currentData.id, currentData.type)
        this.setData({
            currentData,
            first: IndexData.isFirst(currentData.index),
            latest: IndexData.isLatest(currentData.index)
        })
    },

    // 获取最新一期数据
    async _getLatest() {
        const currentData = await IndexData.getLatest()
        this._getLikeStatus(currentData.id, currentData.type)
        if (currentData.index == 1) {
            this.setData({
                first: true,
                latest: true
            })
        }
        this.setData({
            currentData
        })
    },

    async _getLikeStatus(id, type) {
        const likeStatus = await Like.getLikeStatus(id, type)
        this.setData({
            likeStatus
        })
    }

})